<?php
/*
+ --------------------------------------------------- +
|  Ineo Article Manager - Version 2.x
|  Copyright 2006-2007, Dan Cryer and William McGann
+ --------------------------------------------------- +

Ineo Article Manager is free software; you can redistribute it and/or modify
it under the terms of version 3 of the GNU General Public License as published by
the Free Software Foundation.

Ineo Article Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Ineo; see the file License.txt.  If not, write to
the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.

*/

/**
* Ineo - Modules - Global
*  
* This module handles all non-specific front end actions.
*
* @package		Ineo
* @subpackage   Modules
* @author		Dan Cryer & William McGann
* @copyright	Dan Cryer & William McGann
* @version		1.0.0
*/
class ineo_mod_global
{
  var $ipsclass;
  var $core;
  
function module_init()
{
	$this->core->load_library('global');
	$this->core->load_template('global');
	
	if ( $this->ipsclass->vars['ineo_idx_cats'] == 1 )
	{
		$this->core->load_library('categories');
		$this->core->load_template('categories');
	}
	
	// make aliases:
	$this->lib_global =& $this->core->global;
	$this->lib_cat    =& $this->core->categories;
}
  
	function overview()
	{
		// set $this->plugins:
		$this->plugins = array(); // internal
		$this->plugs   = array(); // passed to templates.
		
		// open plugins dir:
		$plugpath = ROOT_PATH.'sources/ineo/overview_plugins/';
		$plugindir = opendir($plugpath);
		
		while( $plugin = readdir($plugindir) )
		{
			// skip anything starting with '.':
			if( substr( $plugin, 0, 1 ) == '.' )
			{
				continue; 
			}
			
			// skip anything not ending in '.php':
			if( substr( $plugin, -4 ) != '.php' )
			{
				continue;
			}
			
			// load plugin:
			require_once($plugpath.$plugin);
			$plug_id    = substr( $plugin, 0, strlen($plugin) - 4 );
			$plug_class = 'overview_plugin_' . $plug_id;
			
			if( class_exists( $plug_class ) )
			{
				$this->plugins[$plug_id] = new $plug_class( $this->core );
				
				if( $this->plugins[$plug_id]->plugin_data['enabled'] == false )
				{
					unset($this->plugins[$plug_id]);
					continue;
				}
			}
			else
			{
				continue;
			}
			
			$data =& $this->plugins[$plug_id]->plugin_data;
			
			$data['plug_id']       = $plug_id;
			
			if( !$data['is_tab'] )
			{
				$data['plugin_output'] = $this->plugins[$plug_id]->get_data();
				$this->plugins[$plug_id]->output = $data['plugin_output'];
			}
			
			// set plugin tab info for this plugin:
			$data =& $this->plugins[$plug_id]->plugin_data;
			
			if( $data['is_tab'] )
			{
				$data['tab_on'] = false;
				$this->plugs[ $data['tab_order'] . '-' . $plug_id ] = $data;
			}
			
		}
		
		closedir( $plugindir );
		ksort($this->plugs);
		
		foreach( $this->plugs as $id => $plug )
		{
			$this->plugs[$id]['tab_on'] = true;
			$parts = explode('-',$id);
			$tid = $parts[1];
			$this->plugs[$id]['plugin_output'] = $this->plugins[$tid]->get_data();
			break;
		}
		
		$this->core->out .= $this->core->templates['global']->index( $this->plugs, $this->plugins );
	}
	
	function index()
	{
		$this->overview();
	}
	
	function art_watchlist()
	{
    // Article Specific Query:
	  $watch['title'] = 'Article';
	  $watch['op']    = 'article';
			
		$query = array( 'select' => 'w.* , a.article_title',
							      'from'   => array( 'ineo_watchlists' => 'w' ),
							      'where'  => 'watch_type = 1 AND watch_user = ' . $this->ipsclass->member['id'],
							      'add_join' => array( 1 => array( 'type' => 'left',
															           'from' => array( 'ineo_articles' => 'a' ),
															           'where' => 'a.article_id = w.watch_id',)
												               )
						      );
	  $this->ipsclass->DB->simple_construct( $query );
		$this->ipsclass->DB->simple_order( 'a.article_title ASC' );
		$this->ipsclass->DB->simple_exec();
		
		$wlist = '';	
		
		while( $res = $this->ipsclass->DB->fetch_row() )
		{
			$wlist .= $this->core->templates['global']->watchlist_row( $watch , $res );
		}
		
		$this->core->out .= $this->core->templates['global']->watchlist_index( $watch , $wlist );
	}
	
	function cat_watchlist()
	{
		$watch['title'] = $this->ipsclass->lang['ineo_watch_category'];
		$watch['op']    = 'cat';
		
		$query = array( 'select' => 'w.* , c.category_name',
							      'from'   => array( 'ineo_watchlists' => 'w' ),
							      'where'  => 'watch_type = 2 AND watch_user = ' . $this->ipsclass->member['id'],
							      'add_join' => array( 1 => array(
                                         'type' => 'left',
															           'from' => array( 'ineo_categories' => 'c' ),
															           'where' => 'c.category_id = w.watch_id',)
												               )
						      );
		$this->ipsclass->DB->simple_construct( $query );
		$this->ipsclass->DB->simple_order( 'c.category_name ASC' );
		$this->ipsclass->DB->simple_exec();
		
		$wlist = '';	
		
		while( $res = $this->ipsclass->DB->fetch_row() )
		{
			$wlist .= $this->core->templates['global']->watchlist_row( $watch , $res );
		}
		
		$this->core->out .= $this->core->templates['global']->watchlist_index( $watch , $wlist );
	}
	
	function watch_add_art()
	{
		$id = $this->ipsclass->input['id'];
		
		// Firstly, delete if there already is one -
		// why they'd want to re-add is beyond me, however.
		
		$this->ipsclass->DB->simple_delete(
											'ineo_watchlists' , 
											'watch_user = ' . $this->ipsclass->member['id'] .
											' AND watch_id = ' . $id .
											' AND watch_type = 1'
										  );
		$this->ipsclass->DB->simple_exec();
		
		// Then add the watch:
		
		$this->ipsclass->DB->do_insert( 
											'ineo_watchlists',
											array( 
													'watch_user' => $this->ipsclass->member['id'],
													'watch_id'   => $id,
													'watch_type' => 1,
												)
											);
		$this->ipsclass->boink_it( $this->core->base_url . 'showarticle=' . $id . '&msg=ineo_sys_artwatch' );
	}
	
	function watch_add_cat()
	{
		$id = $this->ipsclass->input['id'];
		
		// Firstly, delete if there already is one -
		// why they'd want to re-add is beyond me, however.
		
		$this->ipsclass->DB->simple_delete(
											'ineo_watchlists' , 
											'watch_user = ' . $this->ipsclass->member['id'] .
											' AND watch_id = ' . $id .
											' AND watch_type = 2'
										  );
		$this->ipsclass->DB->simple_exec();
		
		// Then add the watch:
		
		$this->ipsclass->DB->do_insert( 
											'ineo_watchlists',
											array( 
													'watch_user' => $this->ipsclass->member['id'],
													'watch_id'   => $id,
													'watch_type' => 2,
												)
											);
		$this->ipsclass->boink_it( $this->core->base_url . 'showcat=' . $id . '&msg=ineo_sys_catwatch' );
	}
	
	function watch_cat_delete()
	{
		$this->ipsclass->DB->simple_delete(
											'ineo_watchlists' , 
											'watch_user = ' . $this->ipsclass->member['id'] .
											' AND watch_id = ' . $this->ipsclass->input['id'] .
											' AND watch_type = 2'
										  );
		$this->ipsclass->DB->simple_exec();
		$this->ipsclass->boink_it( $this->core->base_url . 'mod=global&op=cat_watchlist&msg=ineo_catwatch_del' );
	}
	
	function watch_art_delete()
	{
		$this->ipsclass->DB->simple_delete(
											'ineo_watchlists' , 
											'watch_user = ' . $this->ipsclass->member['id'] .
											' AND watch_id = ' . $this->ipsclass->input['id'] .
											' AND watch_type = 1'
										  );
		$this->ipsclass->DB->simple_exec();
		$this->ipsclass->boink_it( $this->core->base_url . 'mod=global&op=art_watchlist&msg=ineo_artwatch_del' );
	}
	
	/**
	* Full Search
	*/
	function full_search()
	{
		$catLib =& $this->core->load_library('categories');
		
		$cat_list = $catLib->select_list_items();
		$this->core->out .= $this->core->templates['skin_ineo_global']->search_page( $cat_list );
	}
	
	/**
	* Do full search
	*/
	function full_search_do()
	{
		$db =& $this->ipsclass->DB;
		
		//----
		// Get categories to search:
		//----
		$categories = $_GET['categories'];
		$categories = $this->core->dblib->query_full_search_categories($categories);		
		//----
		// Get keywords to search:
		//----
		$keys = $this->ipsclass->input['keywords'];
		$keywords = $this->prepare_fulltext_keywords($this->ipsclass->input['keywords']);
		$keywords = trim($keywords);
		
		//----
		// Start / Limit / Order :
		//----
		$order_in    = $this->ipsclass->input['order'];
		$start = intval( $this->ipsclass->input['st'] );
		$order = ( $order_in == 'relevance' ) ? 'relevance' : 'c.content_date';
		
		//----
		// Queued Articles?
		//----
		$queued = ($this->ipsclass->member['g_ineo_ismod']) ? '' : ' AND a.article_is_queued = 0';
		
		// Make sure we set up DB lib's bool mode:
		$this->core->dblib->check_bool_mode();
		
		//--------------------
		// Get result count:
		$db->query( $this->core->dblib->query_full_search_count($keywords,$queued,$categories) );	
		
		$res = $db->fetch_row();
		
		if( $res['result_count'] == 0 )
		{
			$this->core->error('survey_says_uhuh',$this->ipsclass->lang['ineo_gen_error']);
			return;
		}
		else
		{
			$search_count = $res['result_count'];
		}
		//--------------------
		
		//--------------------
		// Perform search query
		$query = $db->query( $this->core->dblib->query_full_search($keywords,$queued,$categories,$start,$order) );
		//--------------------
		
		$info = array('string' => 'op=full_search_do&keywords=' . $keys,'total'  => $search_count,	'start'  => $start);
					
		$this->search_results_from_query($query,$info);
		
	}
	
	function author_search_do()
	{
		if( empty($this->ipsclass->input['author']) )
		{
			$this->core->error('survey_says_uhuh',$this->ipsclass->lang['ineo_gen_error']);
			return;
		}
		
		$start = empty($this->ipsclass->input['st']) ? 0 : intval($this->ipsclass->input['st']);
		
		$username = mysql_real_escape_string($this->ipsclass->input['author']);
		
		$this->ipsclass->DB->simple_construct( array('select' => 'id' , 'from' => 'members' , 'where' => 'members_display_name = \''.$username.'\'') );
		$mem = $this->ipsclass->DB->simple_exec();
		
		if( $this->ipsclass->DB->get_num_rows() == 0 )
		{
			$this->core->error('survey_says_uhuh',$this->ipsclass->lang['ineo_gen_error']);
			return;
		}
		
		$mem = $this->ipsclass->DB->fetch_row();
		$member_id = $mem['id'];
		
		$this->ipsclass->DB->simple_construct( 
												array( 
														'select' => 'count( c.content_id ) as result_count' , 
														'from' => array('ineo_content'=>'c'),
														'add_join' => array( 1 => 
																					array( 
																						'type' => 'left',
																						'from' => array('ineo_articles' => 'a'),
																						'where' => 'a.article_content = c.content_id',	
																						)
																			),
														'where' => 'c.content_author = ' . $member_id . ' and a.article_title IS NOT NULL',
													)
												);
		$query = $this->ipsclass->DB->simple_exec();
		$res = $this->ipsclass->DB->fetch_row();
		
		if( $res['result_count'] == 0 )
		{
			$this->core->error('survey_says_uhuh',$this->ipsclass->lang['ineo_gen_error']);
			return;
		}
		else
		{
			$result_count = $res['result_count'];
		}
		
		$this->ipsclass->DB->simple_construct( 
												array( 
														'select' => 'c.*,a.*' , 
														'from' => array('ineo_content'=>'c'),
														'add_join' => array( 1 => 
																					array( 
																						'type' => 'left',
																						'from' => array('ineo_articles' => 'a'),
																						'where' => 'a.article_content = c.content_id',	
																						)
																			),
														'where' => 'c.content_author = ' . $member_id . ' and a.article_title IS NOT NULL',
													)
												);
		$this->ipsclass->DB->simple_order('c.content_date DESC');
		$this->ipsclass->DB->simple_limit($start.', 20');
		$query = $this->ipsclass->DB->simple_exec();
		
		$info = array(
						'string' => 'op=author_search_do&author=' . $username,
						'total'  => $result_count,
						'start'  => $start,
					 );
		
		$this->search_results_from_query($query,$info);
	}
	
	function search_results_from_query( $query , $search_info )
	{
		//--------------------
		// Loop results and use templates for row HTML:
		$results = '';
		
		while( $article = $this->ipsclass->DB->fetch_row( $query ) )
		{
			$article['article_date_text'] = $this->ipsclass->get_date($article['article_edited_date'],'');
			
			$results .= $this->core->templates['skin_ineo_global']->full_search_results_row( $article );
		}
		//--------------------
		
		
		//--------------------
		// Build page links and dump them + results into the search results template:
		$pages = $this->ipsclass->build_pagelinks( array( 'TOTAL_POSS' => $search_info['total'],
			                                              'PER_PAGE'   => 20,
			                                              'CUR_ST_VAL' => $search_info['start'],
			                                              'BASE_URL'   => "{$this->ipsclass->base_url}autocom=ineo&mod=global&{$search_info['string']}"
														) 
													);
		
		$this->core->out .= $this->core->templates['skin_ineo_global']->full_search_results( $results , $pages );
		//--------------------
	}
	
	/**
	* Takes an array of category ID's and intvals them all, then implodes with commas.
	*/
	function safe_int_ids($array)
	{
		$safe = array();
		
		foreach( $array as $val )
		{
			$safe[] = intval($val);
		}
		
		return implode(',',$safe);
	}
	
	function prepare_fulltext_keywords($words="")
    {
		// Clean and remove crap:
    	$words = trim( rawurldecode($words) );
    	$words = str_replace( '|', "&#124;", $words );
    	$words = str_replace( "&quot;", '"', $words );
    	$words = str_replace( "&gt;"  , ">", $words );
    	$words = str_replace( "%"     , "" , $words );
    	
    	// Take words out of quotes:
    	if ( preg_match( "#^\"(.+?)\"$#", $words ) )
    	{
    		return $words;
    	}
    	
    	// Remove words that are used regularly:
    	$words = preg_replace( "/^(?:img|quote|code|html|javascript|a href|color|span|div|border|style)$/", "", $words );
    	   
		// Filter keywords like and/or/not for their ftext counterparts!
 	
    	// AND
    	$words = preg_replace( "/\s+and\s+/i", " ", $words );
    	
    	// NOT
    	$words = preg_replace( "/\s+not\s+/i", " -", $words );
    	
    	// OR
    	$words = preg_replace( "/\s+or\s+/i", ' ~', $words );
    	    	    	
    	$words = preg_replace( "/~/", "", $words );
    	    	
    	return "+".$words;
    }
}

?>